package com.xhtt.modules.sys.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhtt.common.exception.RRException;
import com.xhtt.common.file.FileInfoModel;
import com.xhtt.common.utils.Constant;
import com.xhtt.common.utils.PageUtils;
import com.xhtt.common.utils.Query;
import com.xhtt.common.utils.RedisUtils;
import com.xhtt.modules.app.form.RegisterForm;
import com.xhtt.modules.cfg.entity.CfgComprod;
import com.xhtt.modules.cfg.entity.CfgIsland;
import com.xhtt.modules.cfg.service.CfgIslandService;
import com.xhtt.modules.sys.dao.SysUserDao;
import com.xhtt.modules.sys.entity.*;
import com.xhtt.modules.sys.model.AddUserToTempTeamModel;
import com.xhtt.modules.sys.model.UserCertModel;
import com.xhtt.modules.sys.service.*;
import com.xhtt.modules.task.model.car.CarTaskUserStatus;
import com.xhtt.modules.task.service.TaskCarTaskService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 系统用户
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2016年9月18日 上午9:46:09
 */
@Service("sysUserService")
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUserEntity> implements SysUserService {
    @Autowired
    private SysUserDeptService sysUserDeptService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysUserCertService sysUserCertService;
    @Autowired
    private SysUserProductService sysUserProductService;
    @Autowired
    private SysDeptService sysDeptService;
    @Autowired
    private SysPositionService positionService;
    @Autowired
    private TaskCarTaskService taskCarTaskService;
    @Autowired
    private SysTempTeamService tempTeamService;
    @Autowired
    private CfgIslandService islandService;
    @Autowired
    private RedisUtils redisUtils;


    @Override
    public PageUtils queryUserPage(Map<String, Object> params) {
        Page<SysUserEntity> page = new Query<SysUserEntity>(params).getPage();
        page.setRecords(baseMapper.queryUserPage(page, params));
        return new PageUtils(page);
    }

    @Override
    public List<String> queryAllPerms(Long userId) {
        return baseMapper.queryAllPerms(userId);
    }

    @Override
    public List<Long> queryAllMenuId(Long userId) {
        return baseMapper.queryAllMenuId(userId);
    }

    @Override
    @Transactional
    public void saveUser(SysUserEntity user) {
        //sha256加密
        String salt = RandomStringUtils.randomAlphanumeric(20);
        user.setPassword(new Sha256Hash(StringUtils.isEmpty(user.getPassword()) ? user.getWorkNo() : user.getPassword(), salt).toHex());
        user.setSalt(salt);
        String workNo = user.getWorkNo();
        int count = this.count(new QueryWrapper<SysUserEntity>().eq(SysUserEntity.WORKNO, workNo));
        if (count > 0) {
            throw new RRException("账号已存在");
        }
        super.save(user);

        //检查角色是否越权
//		checkRole(user);

        //保存用户与部门关系
        List<Long> userIdList = new ArrayList<>();
        userIdList.add(user.getUserId());
        sysUserDeptService.saveOrUpdate(userIdList, user.getDeptIdList());

    }

    @Override
    @Transactional
    public void update(SysUserEntity user) {
        SysUserEntity db = this.getById(user.getUserId());
        if (StringUtils.isBlank(user.getPassword())) {
            user.setPassword(null);
        } else {
            user.setPassword(new Sha256Hash(user.getPassword(), db.getSalt()).toHex());
        }

        if (!db.getWorkNo().equals(user.getWorkNo())) {
            user.setPassword(new Sha256Hash(user.getWorkNo(), db.getSalt()).toHex());
        }
        int count = this.count(new QueryWrapper<SysUserEntity>().eq(SysUserEntity.WORKNO, user.getWorkNo()).ne(SysUserEntity.USERID, user.getUserId()));
        if (count > 0) {
            throw new RRException("账号已存在");
        }
        this.updateById(user);

        //检查角色是否越权
//		checkRole(user);

        //保存用户与部门关系
        List<Long> userIdList = new ArrayList<>();
        userIdList.add(user.getUserId());
        sysUserDeptService.saveOrUpdate(userIdList, user.getDeptIdList());
    }

    @Override
    @Transactional
    public void deleteBatch(Long[] userId) {
        this.removeByIds(Arrays.asList(userId));
        //删除用户与部门的关系
        sysUserDeptService.remove(new QueryWrapper<SysUserDeptEntity>().in(SysUserDeptEntity.USERID, Arrays.asList(userId)));
    }

    @Override
    public boolean updatePassword(Long userId, String password, String newPassword) {
        SysUserEntity userEntity = new SysUserEntity();
        userEntity.setPassword(newPassword);
        return this.update(userEntity,
                new QueryWrapper<SysUserEntity>().eq(SysUserEntity.USERID, userId).eq(SysUserEntity.PASSWORD, password));
    }

    @Override
    @Transactional
    public void register(RegisterForm form) {
        Integer type = form.getType();
        String uuid = form.getUuid();
        String code = form.getCode();
//        if (StringUtils.isEmpty(redisUtils.get(uuid))) {
//            throw new RRException("验证码已过期");
//        }
//        if (!redisUtils.get(uuid).equals(code)) {
//            throw new RRException("验证码不正确");
//        }
        String companyName = form.getCompanyName();
        int count = sysRoleService.count(new QueryWrapper<SysRoleEntity>().eq(SysRoleEntity.NAME, companyName).eq(SysRoleEntity.TYPE, type).eq(SysRoleEntity.PARENTID, -1));
        if (count > 0) {
            throw new RRException("名称已存在");
        }

        SysRoleEntity role = new SysRoleEntity();
        role.setName(companyName);
        List<Long> menus = new ArrayList<>();
        sysRoleService.save(role);

        if (1 == type) {
            //设置企业基本信息
        }
        if (2 == type) {
            //设置机构基本信息
        }


        SysUserEntity user = new SysUserEntity();
        user.setUsername(form.getUserName());
        count = this.count(new QueryWrapper<SysUserEntity>().eq(SysUserEntity.USERNAME, companyName));
        if (count > 0) {
            throw new RRException("用户名已存在");
        }
        user.setPassword(form.getPassword());
        user.setStatus(1);
        this.save(user);

        //保存用户与企业的关系啦
        SysUserDeptEntity ur = new SysUserDeptEntity();
        ur.setDeptId(role.getRoleId());
        ur.setUserId(user.getUserId());
        sysUserDeptService.save(ur);
    }


    @Override
    public PageUtils queryWorkUserPage(Map<String, Object> params) {
        Page<SysUserEntity> page = new Query<SysUserEntity>(params).getPage();
        page.setRecords(baseMapper.queryWorkUserPage(page, params));
        return new PageUtils(page);
    }

    @Override
    public List<SysUserCertEntity> workUserCerts(Integer userId) {
        List<SysUserCertEntity> list = sysUserCertService.list(new QueryWrapper<SysUserCertEntity>().eq(SysUserCertEntity.USERID, userId));
        list.forEach(cert -> {
            if (StringUtils.isNotEmpty(cert.getFile())) {
                cert.setFileInfoModel(JSON.parseObject(cert.getFile(), FileInfoModel.class));
            }
        });
        return list;
    }

    @Override
    @Transactional
    public void updateWorkUserCerts(UserCertModel userCertModel) {
        Integer userId = userCertModel.getUserId();

        //全删全增
        sysUserProductService.remove(new LambdaQueryWrapper<SysUserProduct>().eq(SysUserProduct::getUserId, userId));
        List<CfgComprod> comprods = userCertModel.getOperComprods();
        if (CollectionUtils.isNotEmpty(comprods)) {
            Set<Integer> productIds = comprods.stream().map(CfgComprod::getId).collect(Collectors.toSet());
            List<SysUserProduct> ups = new ArrayList<>();
            SysUserProduct up;
            for (Integer pid : productIds) {
                up = new SysUserProduct();
                up.setUserId(userId);
                up.setProductId(pid);
                ups.add(up);
            }
            if (ups.size() > 0) {
                sysUserProductService.saveBatch(ups);
            }
        }

        List<SysUserCertEntity> list = userCertModel.getList();
        //全删全增
        sysUserCertService.remove(new QueryWrapper<SysUserCertEntity>().eq(SysUserCertEntity.USERID, userId));
        if (CollectionUtils.isNotEmpty(list)) {
            list.forEach(userCertEntity -> {
                userCertEntity.setUserId(userId);
                userCertEntity.setFile(JSON.toJSONString(userCertEntity.getFileInfoModel()));
            });
            sysUserCertService.saveBatch(list);
        }
    }

    @Override
    public List<SysDeptEntity> deptTeamUser() {
        List<SysDeptEntity> list = sysDeptService.tree(Collections.EMPTY_MAP);
        getCarTaskChilerenUsers(list);
        return list;
    }

    @Override
    public List<SysDeptEntity> teamUser() {
        List<SysDeptEntity> list = sysDeptService.tree(Collections.EMPTY_MAP);
        getInsTaskChilerenUsers(list);
        return list;
    }

    @Override
    public List<SysUserEntity> tempTeamUserList(SysUserEntity user) {
//        this.list(new LambdaQueryWrapper<SysUserEntity>().eq(SysUserEntity::getTempTeam, 1).select(SysUserEntity::getUserId, SysUserEntity::getName));
        return null;
    }

    @Override
    public List<SysDeptEntity> deptUser() {
        Map<String, Object> map = new HashMap<>();
        map.put("withoutTeam", 1);
        List<SysDeptEntity> list = sysDeptService.tree(map);
        getCommonChilerenUsers(list);
        return list;
    }

    @Override
    public List<CarTaskUserStatus> zhuangcheTeamUser(Integer loadAreaType, SysUserEntity user) {
        List<CarTaskUserStatus> list = new ArrayList<>();
//        Integer deptId = Integer.valueOf(user.getDeptId());
        //全公司只有一个叫 装车组的组 就是装车组，根据名字来判断的2b设计
        SysDeptEntity team = sysDeptService.getOne(new LambdaQueryWrapper<SysDeptEntity>().eq(SysDeptEntity::getType, 2).eq(SysDeptEntity::getName, Constant.ZCZ).select(SysDeptEntity::getDeptId));
        if (null == team) {
            return list;
        }
//        if (null == user.getTeamId()) {
//            return list;
//        }
        // 查询该组在线的人员
        List<SysUserEntity> userList = this.list(new LambdaQueryWrapper<SysUserEntity>().eq(SysUserEntity::getTeamId, team.getDeptId()).eq(null != loadAreaType, SysUserEntity::getLoadAreaType, loadAreaType).eq(SysUserEntity::getLoginStatus, 1));
        for (SysUserEntity u : userList) {
            list.add(getCarTaskUserStatus(u));
        }
        return list;
    }

    @Override
    public List<CarTaskUserStatus> zhuangcheTempTeamUser(Integer loadAreaType, SysUserEntity user) {
        List<CarTaskUserStatus> list = new ArrayList<>();
        //跟上面一样的sb逻辑
        SysDeptEntity team = sysDeptService.getOne(new LambdaQueryWrapper<SysDeptEntity>().eq(SysDeptEntity::getType, 2).eq(SysDeptEntity::getName, Constant.ZCZ).select(SysDeptEntity::getDeptId));
        if (null == team) {
            return list;
        }

//        if (null == user.getTeamId()) {
//            return list;
//        }
        List<SysUserEntity> userList = baseMapper.zhuangcheTempTeamUser(team.getDeptId(), loadAreaType);
        for (SysUserEntity u : userList) {
            list.add(getCarTaskUserStatus(u));
        }
        return list;
    }

    /**
     * 人员转化
     *
     * @param u
     * @return
     */
    private CarTaskUserStatus getCarTaskUserStatus(SysUserEntity u) {
        String positionName = "";
        if (null != u.getPositionId()) {
            positionName = positionService.getOne(new LambdaQueryWrapper<SysPositionEntity>().eq(SysPositionEntity::getPositionId, u.getPositionId()).select(SysPositionEntity::getPositionId, SysPositionEntity::getName)).getName();
        }
        return new CarTaskUserStatus(u.getUserId().intValue(), u.getName(), getCarUserStatus(u.getUserId()), positionName, null, false);
    }

    @Override
    public void addUserToTempTeam(SysUserEntity user, AddUserToTempTeamModel model) {
        List<Integer> userIds = model.getUserIds();
        ArrayList<Integer> userIds_temp = new ArrayList<>();
        userIds_temp.addAll(userIds);
        Integer loadAreaType = model.getLoadAreaType();
        //跟上面一样的2b逻辑
        SysDeptEntity team = sysDeptService.getOne(new LambdaQueryWrapper<SysDeptEntity>().eq(SysDeptEntity::getType, 2).eq(SysDeptEntity::getName, Constant.ZCZ).select(SysDeptEntity::getDeptId));
        if (null == team) {
            throw new RRException("没有装车组");
        }
        Integer teamId = team.getDeptId();
//        Integer teamId = user.getTeamId();
//        if (null == teamId) {
//            throw new RRException("没有组");
//        }
        List<SysTempTeam> list = tempTeamService.list(new LambdaQueryWrapper<SysTempTeam>().eq(SysTempTeam::getTeamId, teamId));
        List<SysTempTeam> newList = new ArrayList<>();
        if (CollectionUtils.isEmpty(list)) {
            userIds.forEach(userId -> {
                SysTempTeam newTempTeam = new SysTempTeam();
                newTempTeam.setTeamId(teamId);
                newTempTeam.setUserId(userId);
                newList.add(newTempTeam);
            });
            tempTeamService.saveBatch(newList);
        } else {
            List<Integer> oldUserIds = list.stream().map(sysTempTeam -> sysTempTeam.getUserId()).collect(Collectors.toList());
            Iterator<Integer> it = userIds.iterator();
            while (it.hasNext()) {
                Integer uid = it.next();
                if (oldUserIds.contains(uid)) {
                    it.remove();
                }
            }
            if (CollectionUtils.isNotEmpty(userIds)) {
                userIds.forEach(userId -> {
                    SysTempTeam newTempTeam = new SysTempTeam();
                    newTempTeam.setUserId(userId);
                    newTempTeam.setTeamId(teamId);
                    newList.add(newTempTeam);
                });
                tempTeamService.saveBatch(newList);
            }
        }
        //最后把这些人的区域更新一下
        if (CollectionUtils.isNotEmpty(userIds_temp)) {
            SysUserEntity u = new SysUserEntity();
            u.setLoadAreaType(loadAreaType);
            this.update(u, new LambdaQueryWrapper<SysUserEntity>().in(SysUserEntity::getUserId, userIds_temp));
        }
    }

    @Override
    @Transactional
    public void removeUserToTempTeam(SysUserEntity user, Integer userId) {
        //跟上面一样的2b逻辑
        SysDeptEntity team = sysDeptService.getOne(new LambdaQueryWrapper<SysDeptEntity>().eq(SysDeptEntity::getType, 2).eq(SysDeptEntity::getName, Constant.ZCZ).select(SysDeptEntity::getDeptId));
        if (null == team) {
            throw new RRException("没有装车组");
        }
        tempTeamService.remove(new LambdaQueryWrapper<SysTempTeam>().eq(SysTempTeam::getTeamId, team.getDeptId()).eq(SysTempTeam::getUserId, userId));
        //还要把这个人从台上踢下来
        islandService.update(new CfgIsland(), new UpdateWrapper<CfgIsland>().set(CfgIsland.USERID, null).eq(CfgIsland.USERID, userId));
    }

    @Override
    public List<CarTaskUserStatus> getUsersByDept(SysDeptEntity dept) {
        List<CarTaskUserStatus> list = new ArrayList<>();
        List<SysUserEntity> users;
        if (dept.getType().intValue() == 1) {
            users = sysUserDeptService.getUsersByDept(dept.getDeptId());//只获取部门下的人，如果部门下的人有组，是不会获取出来的
        } else {
            users = this.list(new LambdaQueryWrapper<SysUserEntity>().eq(SysUserEntity::getTeamId, dept.getDeptId()));//获取组里面的人
        }
        if (CollectionUtils.isEmpty(users)) {
            return list;
        }
        for (SysUserEntity u : users) {
            list.add(getCarTaskUserStatus(u));
        }
        return list;
    }

    @Override
    public SysUserEntity getTeamLeader(Integer teamId) {
        return baseMapper.getTeamLeader(teamId);
    }

    @Override
    public SysUserEntity getTeamLeaderByUser(Integer userId) {
        return baseMapper.getTeamLeaderByUser(userId);
    }

    @Override
    public PageUtils listByDeptTeam(Map<String, Object> params) {
        Integer type = Integer.valueOf(params.get("type").toString());
        Integer deptId = Integer.valueOf(params.get("deptId").toString());
        Page<SysUserEntity> page = new Query<SysUserEntity>(params).getPage();
        if (1 == type) {
            List<SysUserEntity> list = baseMapper.listByDept(page, deptId);
            page.setRecords(list);
        } else {
            List<SysUserEntity> list = baseMapper.listByTeam(page, deptId);
            page.setRecords(list);
        }
        return new PageUtils(page);
    }

    @Override
    public Map<String, Integer> userClassCount() {
        List<SysUserEntity> list = this.list(new LambdaQueryWrapper<SysUserEntity>().eq(SysUserEntity::getLoginStatus, 1).select(SysUserEntity::getUserId, SysUserEntity::getTeamId));
        int all = list.size();
        int car = 0;
        int pot = 0;
        Map<String, Integer> map = new HashMap<>();
        //从这些人中过滤出装车组人员
        if (all > 0) {
            SysDeptEntity team = sysDeptService.getOne(new LambdaQueryWrapper<SysDeptEntity>().eq(SysDeptEntity::getType, 2).eq(SysDeptEntity::getName, Constant.ZCZ).select(SysDeptEntity::getDeptId));
            if (null == team) {
                car = 0;
            } else {
                Long l = list.stream().filter(u -> null != u.getTeamId() && u.getTeamId().intValue() == team.getDeptId().intValue()).count();
                car = l.intValue();
            }
            pot = all - car;
        }
        map.put("all", all);
        map.put("car", car);
        map.put("pot", pot);
        return map;
    }

    @Override
    public List<SysUserEntity> getDeptLeaderByTeam(Integer teamId) {
        return baseMapper.getDeptLeaderByTeam(teamId);
    }

    @Override
    public List<SysUserEntity> getDeptLeaderByDept(Integer deptId) {
        return baseMapper.getDeptLeaderByDept(deptId);
    }

    @Override
    public String getUserWithDept(Integer userId) {
        return baseMapper.getUserWithDept(userId);
    }

    @Override
    public int getZCZCount(Set<Integer> userIds) {
        int count = baseMapper.getZCZCount(userIds, Constant.ZCZ);
        return count;
    }

    /**
     * 通用的(没有组)
     *
     * @param list
     */
    private void getCommonChilerenUsers(List<SysDeptEntity> list) {
        for (SysDeptEntity dp : list) {
            List<SysDeptEntity> children = dp.getChildren();
            if (CollectionUtils.isNotEmpty(children)) {
                getCarTaskChilerenUsers(children);
            }
            List<SysUserEntity> users = this.list(new LambdaQueryWrapper<SysUserEntity>().eq(SysUserEntity::getTeamId, dp.getDeptId()).select(SysUserEntity::getUserId, SysUserEntity::getName));
            List<CarTaskUserStatus> tusList = new ArrayList<>();
            CarTaskUserStatus tus;
            for (SysUserEntity su : users) {
//                    String status = getCarUserStatus(su.getUserId());
                tus = new CarTaskUserStatus(su.getUserId().intValue(), su.getName(), null, "", su.getTeamId(), false);
                tusList.add(tus);
            }
            dp.setCarTaskUserStatusList(tusList);

        }
    }

    /**
     * 排车任务中要用的
     *
     * @param list
     */
    private void getCarTaskChilerenUsers(List<SysDeptEntity> list) {
        for (SysDeptEntity dp : list) {
            List<SysDeptEntity> children = dp.getChildren();
            if (CollectionUtils.isNotEmpty(children)) {
                getCarTaskChilerenUsers(children);
            }
            //如果是组那就往里面加人，反正组也没有下级，所以不用再往下遍历
            else if (2 == dp.getType().intValue()) {
                List<SysUserEntity> users = this.list(new LambdaQueryWrapper<SysUserEntity>().eq(SysUserEntity::getTeamId, dp.getDeptId()).select(SysUserEntity::getUserId, SysUserEntity::getName));
                List<CarTaskUserStatus> tusList = new ArrayList<>();
                CarTaskUserStatus tus;
                for (SysUserEntity su : users) {
                    String status = getCarUserStatus(su.getUserId());
                    tus = new CarTaskUserStatus(su.getUserId().intValue(), su.getName(), status, "", su.getTeamId(), false);
                    tusList.add(tus);
                }
                dp.setCarTaskUserStatusList(tusList);
            }
        }
    }

    /**
     * 巡检任务中要用的
     *
     * @param list
     */
    private void getInsTaskChilerenUsers(List<SysDeptEntity> list) {
        for (SysDeptEntity dp : list) {
            List<SysDeptEntity> children = dp.getChildren();
            if (CollectionUtils.isNotEmpty(children)) {
                getInsTaskChilerenUsers(children);
            }
            //如果是组那就往里面加人，反正组也没有下级，所以不用再往下遍历
            else if (2 == dp.getType().intValue()) {
                List<SysUserEntity> users = this
                        .list(new LambdaQueryWrapper<SysUserEntity>()
                                .eq(SysUserEntity::getTeamId, dp.getDeptId())
                                .select(SysUserEntity::getUserId, SysUserEntity::getName, SysUserEntity::getTeamId));
                List<CarTaskUserStatus> tusList = new ArrayList<>();
                CarTaskUserStatus tus;
                for (SysUserEntity su : users) {
//                    String status = getCarUserStatus(su.getUserId());
                    tus = new CarTaskUserStatus(su.getUserId().intValue(), su.getName(), "", "", su.getTeamId(), true);
                    tusList.add(tus);
                }
                dp.setCarTaskUserStatusList(tusList);
            }
        }
    }

    /**
     * 算排车任务用户的状态（空闲或忙）
     *
     * @param userId
     * @return
     */
    private String getCarUserStatus(Long userId) {
        LocalDateTime time = taskCarTaskService.getUserFinishTime(userId.intValue());
        if (LocalDateTime.MIN.equals(time)) {
            return "从未做过任务";
        } else if (null == time) {
            return "任务中";
        } else {
            LocalDateTime now = LocalDateTime.now();
            Duration d = Duration.between(time, now);
            long mins = d.toMinutes();//相差分钟数
            return "空闲中：累计时间 " + (mins < 0 ? 0 : mins) + "分钟";
        }
    }


    /**
     * 检查角色是否越权
     */
    private void checkRole(SysUserEntity user) {
//        if (user.getRoleIdList() == null || user.getRoleIdList().size() == 0) {
//            return;
//        }
//        //如果不是超级管理员，则需要判断用户的角色是否自己创建
//        if (user.getCreateUserId() == Constant.SUPER_ADMIN) {
//            return;
//        }
//
//        //查询用户创建的角色列表
//        List<Long> roleIdList = sysRoleService.queryRoleIdList(user.getCreateUserId());
//
//        //判断是否越权
//        if (!roleIdList.containsAll(user.getRoleIdList())) {
//            throw new RRException("新增用户所选角色，不是本人创建");
//        }
    }

    @Override
    public List<Integer> queryAuth(SysUserEntity user) {

        // 用户id
        Integer userId = user.getUserId().intValue();
        // 组id
        Integer teamId = user.getTeamId();
        // 角色(中文名称)
        String roleName = user.getRoleName();

        // 系统管理员
        if (userId.equals(Constant.SUPER_ADMIN) || roleName.equals("Admin")) {
            List<SysUserDeptEntity> sysUserDeptEntities = sysUserDeptService.list();
            return sysUserDeptEntities.stream().map(e -> e.getUserId().intValue()).collect(Collectors.toList());
        } else {

            // 组成员
            if (teamId != null) {
                // 组长
                SysUserEntity leader = getTeamLeaderByUser(userId);
                if (roleName.equals("Key User") && leader.getUserId().intValue() == userId) {
                    List<SysUserEntity> users = this.list(new LambdaQueryWrapper<SysUserEntity>().eq(SysUserEntity::getTeamId, teamId));
                    return users.stream().map(e -> e.getUserId().intValue()).collect(Collectors.toList());
                }

                // 部门成员
            } else {

                // 部门管理员
                if (roleName.equals("Expert User")) {
                    // 获取该部门下所有子部门
                    List<String> dept = sysDeptService.getChildDept(Integer.parseInt(user.getDeptId()));
                    List<SysUserDeptEntity> sysUserDeptEntities = sysUserDeptService
                            .list(new LambdaQueryWrapper<SysUserDeptEntity>()
                                    .in(SysUserDeptEntity::getDeptId, dept));
                    return sysUserDeptEntities.stream().map(e -> e.getUserId().intValue()).collect(Collectors.toList());
                }
            }
        }
        return Collections.singletonList(userId);
    }
}
